package com.example.test003;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
//import javafx.scene.input.DataFormat;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.ibatis.annotations.Mapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
//import sun.security.tools.PathList;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.zip.GZIPInputStream;

@MapperScan("com.example.test003.mapper")
@Component
@SpringBootApplication
@EnableScheduling
public class Test003Application {

    public static void main(String[] args) {
        SpringApplication.run(Test003Application.class, args);
    }

    //删除7天数据
    //@Scheduled(cron = "50 53 7 ? * * ")
    //@Scheduled(cron = "0 50 11 ? * * ")
    public static void deleteSevenDay() throws Exception {
        System.out.println(DateFormat.getDateTimeInstance().format(new Date()));
        // 连接数据库
        Connection connection = JDBCUtils.getConnection();
        QueryRunner runner = new QueryRunner();
        String sql0="delete from seven_days";
        runner.update(connection,sql0);
        JDBCUtils.close(connection);
        System.out.println("删除7天数据");
    }

    //下载新的7天数据
    //@Scheduled(cron = "0 55 7 ? * * ")
    //@Scheduled(cron = "20 50 11 ? * * ")
    public static void downloadSevenDay() throws Exception {
        System.out.println(DateFormat.getDateTimeInstance().format(new Date()));
        Set<String> loggers = new HashSet<>(Arrays.asList("org.apache.http"));
        for (String log : loggers) {
            Logger logger = (Logger) LoggerFactory.getLogger(log);
            logger.setLevel(Level.INFO);
            logger.setAdditive(false);
        }
        System.out.println("开始执行1");

        // 连接数据库
        Connection connection = JDBCUtils.getConnection();
        QueryRunner runner = new QueryRunner();

        System.out.println("开始执行2");
        // 读取文件
        ClassPathResource classpathResource = new ClassPathResource("city.txt");
        InputStream inputStream = classpathResource.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line = "";
        String[] arrs = null;
        List<String> dateList = new ArrayList<>();

        System.out.println("开始执行3");
        while ((line = br.readLine()) != null) {
            try {
                arrs = line.split("-");
                System.out.println(arrs[0] + ":" + arrs[1]);

                // 网站地址
                String result = HtmlUtil.getResult("https://www.tianqi.com/" + arrs[1] + "/7/");
                Document document = Jsoup.parse(result);
                Elements elements;


                // 获取日期和星期
                elements = document.select("span[class=fl]");
                List<String> dayList = new ArrayList<>();

                for (Element item : elements) {
                    dateList.add(item.text());
                }
                System.out.println(dateList);  // 日期
                //获取星期
                elements = document.select("span[class=fr]");
                for (Element item : elements) {
                    dayList.add(item.text());
                }
                System.out.println(dayList);  // 今天或明天等

                // 获取天气情况
                elements = document.select("div[class=weaul_z]");
                List<String> weatherList = new ArrayList<>();
                int num=0;
                for (Element item : elements) {
                    if(num%2==0){
                        weatherList.add(item.text());
                    }
                    num++;
                }
                System.out.println(weatherList);  // 天气情况

                // 获取温度，最高温和最低温
                elements = document.select("div[class=weaul_z]>span");
                List<String> highTempList = new ArrayList<>();
                List<String> lowTempList = new ArrayList<>();
                int num2=0;
                for (Element item : elements) {
                    if(num2%2==0){
                        lowTempList.add(item.text()+"°C");
                        num2++;
                    }else {
                        highTempList.add(item.text()+"°C");
                        num2++;
                    }
                }
                System.out.println(highTempList);  // 最高温度
                System.out.println(lowTempList); // 最低温度


                System.out.println("--------------------分隔线--------------------------");
                // 封装结果，每天一行
                List<Map<String, String>> list = new ArrayList<>();
                for (int j = 0; j < 7; j++) {
                    Map<String, String> map = new LinkedHashMap<>();
                    map.put("date", dateList.get(j));
                    map.put("day", dayList.get(j));
                    map.put("weather", weatherList.get(j));
                    map.put("highTemp", highTempList.get(j));
                    map.put("lowTemp", lowTempList.get(j));
                    list.add(map);
                }
                list.forEach(System.out::println);

                System.out.println("--------------------分隔线--------------------------");
                // 将天气元素存入数据库
                for (int j = 0; j < 7; j++) {
                    //String sql = "INSERT INTO seven_days(city,date1,day1,weather,hightem,lowtem,winddirect,windspeed) values(?,?,?,?,?,?,?,?)";
                    String sql="insert into seven_days values(?,?,?,?,?,?,?,?)";
                    runner.update(connection, sql, arrs[0], dateList.get(j), dayList.get(j), weatherList.get(j), highTempList.get(j), lowTempList.get(j),null,null);
                    System.out.println("成功");
                }
            }catch (Exception e){
                System.out.println(e);
            }

        }

        // 关闭资源
        br.close();

        ClassPathResource classPathResource1=new ClassPathResource("TestOneDay.txt");
        InputStream inputStream1=classPathResource1.getInputStream();
        BufferedReader br1 = new BufferedReader(new InputStreamReader(inputStream1, "UTF-8"));
        String line1 = "";
        String[] arrs1 = null;
        while ((line1 = br1.readLine()) != null) {
            try {
                arrs1 = line1.split("-");
                System.out.println(arrs1[0] + ":" + arrs1[1]);

                // 网站地址
                String result = HtmlUtil.getResult("https://weather.cma.cn/web/weather/" + arrs1[1] + ".html");
                Document document = Jsoup.parse(result);
                Elements elements;

                List<String> highTemList=new ArrayList<>();
                List<String> lowTemList=new ArrayList<>();
                elements=document.select("div[class=high]");
                for (Element element:elements) {
                    highTemList.add(element.text());
                }
                System.out.println(highTemList);
                elements=document.select("div[class=low]");
                for (Element element:elements) {
                    lowTemList.add(element.text());
                }
                System.out.println(lowTemList);

                List<String> winddirectList=new ArrayList<>();
                List<String> windspeedList=new ArrayList<>();
                elements=document.select("div[class=day-item]");
//            for (Element element:elements) {
//                winddirectList.add(element.text());
//            }
                int num3=0;
                for (Element element:elements) {
                    if (num3%7==2){
                        winddirectList.add(element.text());
                        num3++;
                    }else if (num3%7==3){
                        if ("微风".equals(element.text())){
                            windspeedList.add("1~2级");
                        }else {
                            windspeedList.add(element.text());
                        }
                        num3++;
                    }else {
                        num3++;
                    }


                }
                System.out.println(winddirectList);
                System.out.println(windspeedList);
                System.out.println("--------------------分隔线--------------------------");
                // 将天气元素存入数据库
                for (int j = 0; j < 7; j++) {
                    //String sql = "INSERT INTO seven_days(city,date1,day1,weather,hightem,lowtem,winddirect,windspeed) values(?,?,?,?,?,?,?,?)";
                    String sql="update seven_days set hightem=?,lowtem=?,winddirect=?,windspeed=? where cityname=? and date1=?";
                    runner.update(connection, sql,highTemList.get(j),lowTemList.get(j),winddirectList.get(j),windspeedList.get(j),arrs1[0],dateList.get(j));
                }
            }catch (Exception e){
                System.out.println(e);
            }

        }
        // 关闭资源
        br.close();
        JDBCUtils.close(connection);
    }


    //删除newoneday数据
//    @Scheduled(cron = "50 46 19 ? * * ")
    @Scheduled(cron = "50 23 0 ? * * ")
    public static void deleteNewOneDay() throws Exception {
        System.out.println(DateFormat.getDateTimeInstance().format(new Date()));
        // 连接数据库
        Connection connection = JDBCUtils.getConnection();
        QueryRunner runner = new QueryRunner();
        String sql0="delete from new_one_day";
        runner.update(connection,sql0);
        JDBCUtils.close(connection);
        System.out.println("删除昨天24小时数据");
    }


    //下载newoneday数据
//    @Scheduled(cron = "5 47 19 ? * * ")
    @Scheduled(cron = "0 24 0 ? * *")
    public static void downloadOneDay() throws Exception{
        System.out.println(DateFormat.getDateTimeInstance().format(new Date()));
        Set<String> loggers = new HashSet<>(Arrays.asList("org.apache.http"));
        for (String log : loggers) {
            Logger logger = (Logger) LoggerFactory.getLogger(log);
            logger.setLevel(Level.INFO);
            logger.setAdditive(false);
        }

        // 连接数据库
        Connection connection = JDBCUtils.getConnection();
        QueryRunner runner = new QueryRunner();

        // 读取文件
        ClassPathResource classPathResource=new ClassPathResource("24h.txt");
        InputStream inputStream=classPathResource.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line = "";
        String[] arrs = null;
        while ((line = br.readLine()) != null) {
            try {


                StringBuffer sb = new StringBuffer();
                arrs = line.split("-");
                System.out.println(arrs[0] + ":" + arrs[1]);

                String urlStr = "https://devapi.qweather.com/v7/weather/24h?location=" + arrs[1] + "&key=6f1c99087cc74fd09547e52066a612cc";
                URL url = new URL(urlStr);

                // 创建HttpURLConnection对象并设置请求方法
                URLConnection con = url.openConnection();

                InputStream is = con.getInputStream();
                GZIPInputStream gzin = new GZIPInputStream(is);
                InputStreamReader isr = new InputStreamReader(gzin, "utf-8");
                BufferedReader reader = new BufferedReader(isr);
                String line1 = null;
                while ((line1 = reader.readLine()) != null) {
                    sb.append(line1 + " ");
                }
                reader.close();
                System.out.println(sb.toString());

                // 将json数据转换为JsonNode对象
                ObjectMapper mapper = new ObjectMapper();
                JsonNode data = mapper.readTree(String.valueOf(sb));

                LocalDate today = LocalDate.now();

                // 创建日期格式化对象
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
                // 格式化日期字符串
                String formattedDate = today.format(formatter);

                // 打印输出
                System.out.println("今天的日期是：" + formattedDate);
                String time=null;
                // 获取temp的值
                //这是临时的，如果是大方县的天气，则存入大方县气象站数据库
                if (arrs[1].equals("101260705")){
                    // 创建日期格式化对象
                    DateTimeFormatter formatter_dafang = DateTimeFormatter.ofPattern("yyyyMMdd");
                    // 格式化日期字符串
                    String formattedDate_dafang = today.format(formatter_dafang);
                    for (int i = 0; i < 24; i++) {

                        if (i<10){
                            time=formattedDate_dafang+"0"+i+"00";
                        }else {
                            time =formattedDate_dafang+ i+"00";
                        }
                        String windDir = data.get("hourly").get(i).get("windDir").asText();//风向
                        String windSpeed = data.get("hourly").get(i).get("windSpeed").asText()+"m/s";//风速
                        String temp = data.get("hourly").get(i).get("temp").asText()+"°C"; //温度
                        String humidity = data.get("hourly").get(i).get("humidity").asText()+"%";//湿度
                        String pressure = data.get("hourly").get(i).get("pressure").asText()+"kpa";//压强
                        String precip = data.get("hourly").get(i).get("precip").asText()+"mm";//降水

                        String sql = "insert into weatherstation_dafang values(?,?,?,?,?,?,?)";
                        runner.update(connection, sql, time, windDir, windSpeed,temp, humidity, pressure,precip);
                    }
                }else {
                    for (int i = 0; i < 24; i++) {
                        if (i<10){
                            time= "0"+i;
                        }else {
                            time = String.valueOf(i);
                        }
                        String tianqi = data.get("hourly").get(i).get("text").asText();
                        String temp = data.get("hourly").get(i).get("temp").asText();
                        String windDir = data.get("hourly").get(i).get("windDir").asText();
                        String windScale = data.get("hourly").get(i).get("windScale").asText() + "级";
                        String windSpeed = data.get("hourly").get(i).get("windSpeed").asText();
                        String precip = data.get("hourly").get(i).get("precip").asText();
                        String humidity = data.get("hourly").get(i).get("humidity").asText();
                        String pressure = data.get("hourly").get(i).get("pressure").asText();
                        String sql = "insert into new_one_day values(?,?,?,?,?,?,?,?,?,?,?)";
                        runner.update(connection, sql, arrs[0], formattedDate, time, tianqi, temp, windDir, windScale, windSpeed, precip, humidity, pressure);
                    }
                }



            }catch (Exception e){
                System.out.println(e);
            }
            // 打印输出
            // System.out.println("tempValue: " + tempValue);
        }
        JDBCUtils.close(connection);
        br.close();
    }

    /**
     * 自动生成txt
     * @throws IOException
     */
    //@Scheduled(cron = "0 30 0 ? * *")
    public static void TestTxt() throws IOException {
        String path="src/main/resources/static/img/city";
        String [] nameList=new File(path).list();//获取到所有的文件名
        System.out.println(nameList[0]);
        System.out.println(nameList[62]);
        for (int i = 0; i < nameList.length; i++) {
            String path2=path+"/"+nameList[i];
            String [] picList=new File(path2).list();
            FileWriter fileWriter=null;
            String txtPath=path+"/"+nameList[i].toString()+"/"+nameList[i].toString()+".txt";
            File file=new File(txtPath);
            file.createNewFile();
            fileWriter=new FileWriter(txtPath);
            BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
            for (int j = 0; j < picList.length; j++) {
                bufferedWriter.write(picList[j]);
                bufferedWriter.write("\n");
                System.out.println(picList[j]);
            }
            bufferedWriter.close();
        }
    }

    //气象视频的下载生成
    //@Scheduled(cron = "0 30 12 ? * *")
    @Scheduled(cron = "20 45 14 ? * *")
    public void test() {
        System.out.println("Start");
        // python脚本的绝对路径，在windows中用"\\"分隔，在Linux中用"/"分隔
        String pyPath = "C:\\Users\\Cold'Rain\\Desktop\\test003\\src\\main\\resources\\python\\All.py";
        // 传入python脚本的参数为”111“
        String[] args1 = new String[]{"C:\\Users\\Cold'Rain\\.conda\\envs\\pytorch\\python.exe",pyPath};

        try {
            // 执行Python文件，并传入参数
            Process process = Runtime.getRuntime().exec(args1);
            // 防止缓冲区满, 导致卡住
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String line;
                    try {
                        BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream(),"UTF-8"));
                        while ((line = stderr.readLine()) != null) {
                            System.out.println("stderr:" + line);
                        }
                    }
                    catch (Exception e) {

                    }

                }
            }.start();

            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String line;
                    try {
                        BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream(),"UTF-8"));
                        while ((line = stderr.readLine()) != null) {
                            System.out.println("stderr:" + line);
                        }
                    }
                    catch (Exception e) {

                    }

                }
            }.start();

            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String line;
                    try {
                        BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream(),"UTF-8"));
                        while ((line = stderr.readLine()) != null) {
                            System.out.println("stderr:" + line);
                        }
                    }
                    catch (Exception e) {

                    }

                }
            }.start();

            System.out.println("==============打印结果==============");
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String line;
                    try {
                        BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream(),"UTF-8"));
                        while ((line = stdout.readLine()) != null) {
                            System.out.println(line);
                        }
                    }
                    catch (Exception e) {

                    }
                }
            }.start();
            //in.close();
            process.waitFor();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("End");
    }

    //雷达图像
//    @Scheduled(cron = "0 0/3 * ? * *")
    public void radar() {
        System.out.println("Start");
        // python脚本的绝对路径，在windows中用"\\"分隔，在Linux中用"/"分隔
        String pyPath = "C:\\Users\\Cold'Rain\\Desktop\\test003\\src\\main\\resources\\python\\get_rad.py";
        // 传入python脚本的参数为”111“
        String[] args1 = new String[]{"C:\\Users\\Cold'Rain\\.conda\\envs\\pytorch\\python.exe",pyPath};

        try {
            // 执行Python文件，并传入参数
            Process process = Runtime.getRuntime().exec(args1);
            // 防止缓冲区满, 导致卡住
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String line;
                    try {
                        BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream(),"UTF-8"));
                        while ((line = stderr.readLine()) != null) {
                            System.out.println("stderr:" + line);
                        }
                    }
                    catch (Exception e) {

                    }

                }
            }.start();


            System.out.println("==============打印结果==============");
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String line;
                    try {
                        BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream(),"UTF-8"));
                        while ((line = stdout.readLine()) != null) {
                            System.out.println(line);
                        }
                    }
                    catch (Exception e) {

                    }
                }
            }.start();
            //in.close();
            process.waitFor();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("End");
    }

    //下载气象站数据
    @Scheduled(cron = "30 0 * * * *")
    //@Scheduled(cron = "30 * * * * *")
    public static void qixiangzhan() throws Exception{
        System.out.println(DateFormat.getDateTimeInstance().format(new Date()));
        try {
            Set<String> loggers = new HashSet<>(Arrays.asList("org.apache.http"));
            for (String log : loggers) {
                Logger logger = (Logger) LoggerFactory.getLogger(log);
                logger.setLevel(Level.INFO);
                logger.setAdditive(false);
            }

            // 连接数据库
            Connection connection = JDBCUtils.getConnection();
            QueryRunner runner = new QueryRunner();

            String loginName = "h230404nxd";
            String password = "h230404nxd";
            String urlStr = "http://www.0531yun.com/api/getToken?loginName=" + loginName + "&password=" + password;

            // 创建URL对象
            URL url = new URL(urlStr);

            // 创建HttpURLConnection对象并设置请求方法
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");

            // 发送请求并获取响应代码
            int responseCode = con.getResponseCode();
            //System.out.println("Response Code : " + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印响应内容
            //System.out.println("Response Content : " + response.toString());
            JSONObject object= JSONObject.parseObject(String.valueOf(response));  //Object类型
            //System.out.println(object);
            String token= (String) object.getJSONObject("data").get("token");
            System.out.println("得到的token"+token);

            String deviceAddr = "21053202";
            String urlStr2 = "http://www.0531yun.com/api/data/getRealTimeDataByDeviceAddr?deviceAddrs=" + deviceAddr;

            // 创建URL对象
            URL url2 = new URL(urlStr2);

            // 创建HttpURLConnection对象并设置请求方法
            HttpURLConnection con2 = (HttpURLConnection) url2.openConnection();
            con2.setRequestMethod("GET");

            // 设置Authorization请求头
            con2.setRequestProperty("Authorization", token);

            // 发送请求并获取响应代码
            int responseCode2 = con.getResponseCode();
            //System.out.println("Response Code : " + responseCode2);

            // 读取响应内容
            BufferedReader in2 = new BufferedReader(new InputStreamReader(con2.getInputStream()));
            String inputLine2;
            StringBuilder response2 = new StringBuilder();

            while ((inputLine2 = in2.readLine()) != null) {
                response2.append(inputLine2);
            }
            in2.close();

            // 打印响应内容
            //System.out.println("Response Content : " + response2.toString());



            //先把String对象转换成json对象
            JSONObject object2= JSONObject.parseObject(String.valueOf(response2));  //Object类型

            JSONArray Arraytemp=object2.getJSONArray("data"); //变成array类型[{}]
            //System.out.println(Arraytemp.getClass());

            JSONObject JsonObjecttemp= (JSONObject) Arraytemp.get(0);//{}
            JSONArray Arraytemp2=JsonObjecttemp.getJSONArray("dataItem"); //[{}]
            //System.out.println(Arraytemp2);

            JSONObject JsonObjecttemp2= (JSONObject) Arraytemp2.get(0);//{}
            JSONArray Arraytemp3=JsonObjecttemp2.getJSONArray("registerItem"); //[{}]

            //JSONObject windlevel= (JSONObject) Arraytemp3.get(0);//{}
            //System.out.println(windlevel.get("data")); //风力。单位级

            JSONObject windspeed= (JSONObject) Arraytemp3.get(1);//{}
            System.out.println("风速"+windspeed.get("data")); //风速。单位m/s


            JSONObject JsonObjecttemp4= (JSONObject) Arraytemp2.get(1);//{}
            JSONArray Arraytemp4=JsonObjecttemp4.getJSONArray("registerItem"); //[{}]
            JSONObject winddirect= (JSONObject) Arraytemp4.get(0);//{}
            System.out.println("风向"+winddirect.get("data")); //风向。单位方向

            JSONObject JsonObjecttemp5= (JSONObject) Arraytemp2.get(2);//{}
            JSONArray Arraytemp5=JsonObjecttemp5.getJSONArray("registerItem"); //[{}]
            JSONObject tem= (JSONObject) Arraytemp5.get(0);//{}

            Double tem1 =Double.valueOf(tem.get("data").toString());
//            double tem2 =Math.floor(tem1);
//            int tem_int = (int)tem2;

            System.out.println("温度"+tem.get("data")); //温度。单位C
            JSONObject humidity= (JSONObject) Arraytemp5.get(1);//{}

            Double hum1 =Double.valueOf(humidity.get("data").toString());
//            double hum2 =Math.floor(hum1);
//            int hum_int = (int)hum2;

            System.out.println("湿度"+humidity.get("data")); //湿度。单位%

            JSONObject JsonObjecttemp6= (JSONObject) Arraytemp2.get(3);//{}
            JSONArray Arraytemp6=JsonObjecttemp6.getJSONArray("registerItem"); //[{}]
            JSONObject pask= (JSONObject) Arraytemp6.get(0);//{}
            System.out.println("压强"+pask.get("data")); //压强。单位kpa

            JSONObject JsonObjecttemp7= (JSONObject) Arraytemp2.get(4);//{}
            JSONArray Arraytemp7=JsonObjecttemp7.getJSONArray("registerItem"); //[{}]
            JSONObject rain= (JSONObject) Arraytemp7.get(0);//{}
            System.out.println("降雨"+rain.get("data")); //降雨。单位mm

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
            String formattedDateTime = now.format(formatter);//将当前日期格式化

            String sql="INSERT INTO weatherstation (`detectedTime`,windDirection,windSpeed,ambientTemperature,ambientHumidity,pressure,rainfall) values(?,?,?,?,?,?,?)";
            runner.update(connection, sql,formattedDateTime,winddirect.get("data"),windspeed.get("data")+"m/s",tem1+"°C",hum1+"%",pask.get("data")+"kpa",rain.get("data")+"mm");
            JDBCUtils.close(connection);
        }catch (Exception e){
            System.out.println(e);
        }finally {
        }

    }

    @Scheduled(cron = "0 0 10 ? * * ")
    public static void deleteFolder(){
        String folderPath = "D:\\Project\\QQFY\\20230102\\tp\\tpCSV";
        String folderPath2 = "D:\\Project\\QQFY\\20230102\\t2m\\t2mCSV";
        String folderPath3 = "D:\\Project\\QQFY\\20230102\\sp\\spCSV";
        String folderPath4 = "D:\\Project\\QQFY\\20230102\\r2\\r2CSV";
        deleteFiles(folderPath);
        deleteFiles(folderPath2);
        deleteFiles(folderPath3);
        deleteFiles(folderPath4);
    }



    //递归删除文件夹
    public static void deleteFiles(String folderPath) {
        File folder = new File(folderPath);

        // 检查文件夹是否存在
        if (!folder.exists()) {
            System.out.println("文件夹不存在！");
            return;
        }

        // 检查是否是文件夹
        if (!folder.isDirectory()) {
            System.out.println("指定路径不是文件夹！");
            return;
        }

        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    // 删除文件
                    file.delete();
                    System.out.println("已删除文件: " + file.getAbsolutePath());
                } else if (file.isDirectory()) {
                    // 递归删除子文件夹中的文件
                    deleteFiles(file.getAbsolutePath());
                }
            }
        }

    }
}
